package com.woniu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.dto.SubjectImportDTO;
import com.woniu.entity.dto.UserLoginDTO;
import com.woniu.mapper.SubjectMapper;
import com.woniu.mapper.UserMapper;
import com.woniu.pojo.Subject;
import com.woniu.pojo.User;
import com.woniu.service.ISubjectService;
import com.woniu.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author xiaotang
 * @since 2025-02-14
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements ISubjectService {
    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public boolean importData(List<SubjectImportDTO> excelData) {
        // 1. 遍历集合
        for(SubjectImportDTO data : excelData){
            // 2. 判断一级分类是否存在，如果存在，不需要任何处理
            Subject parentSubject = subjectMapper.isExistsParent(data.getOneTitle());
            if(parentSubject == null){
                // 3. 如果一级分类不存在，保存一级分类
                parentSubject = new Subject();
                parentSubject.setTitle(data.getOneTitle());
                parentSubject.setParentId(0L);
                subjectMapper.insert(parentSubject);
            }
            // 4. 判断二级分类是否存在，如果存在不需要任何处理
            Subject secondSubject = subjectMapper.isExistsSecond(data.getTowTitle());
            // 5. 如果二级分类不存在，保存二级分类（关键点：设置二级分类的父ID---就是一级分类的ID）
            if(secondSubject == null){
                secondSubject = new Subject();
                secondSubject.setTitle(data.getTowTitle());
                secondSubject.setParentId(parentSubject.getId());
                subjectMapper.insert(secondSubject);
            }
        }
        // 6. 返回结果
        return true;
    }

    @Override
    public List<Subject> listSubject() {

        return subjectMapper.listSubjectByClassify();
    }

    /**
     * 将方法的返回值保存到redis缓存中
     * @return
     */
    @Cacheable(value = "subject", key = "'index:two'")
    @Override
    public List<Subject> listIndexTwo() {
        return subjectMapper.listIndexTwo();
    }
}